﻿const router = require('koa-router')()
const orderModel = require('../models/order')
const goodsModel = require("../models/good")
//引入日期区间判断函数
const screenArray = require("../config/screenArray")
//引入生成卡号激活码函数
const randow = require("../config/randomNumber")
const keyaccountModel = require("../models/keyaccount")
const partnerModel = require("../models/partner")
router.prefix('/api')



//修改订单状态
router.post("/checkOrders", async (ctx) => {
    ctx.body = 200
    let data = ctx.request.body
    let { keyword, order_number } = data
    let orderRes = await orderModel.findOne({ order_number: order_number })

    //获取订单商品名字
    let product_name = orderRes.product_name
    //获取订单销售姓名
    let Sales_name = orderRes.name
    let partnerRes = await partnerModel.findOne({ partner_name: Sales_name })
    //获取合伙人/大客户销量
    let sales_number

    let keyaccountRes = await keyaccountModel.findOne({ Sales_name: Sales_name })


    //获取商品数量
    let order_quantity = orderRes.order_quantity

    //获取支付状态
    let pay_status = orderRes.pay_status
    //获取订单审核状态
    let order_status = orderRes.order_status
    let cardArr = []
    //审核订单
    if (pay_status == 1 && order_status != 1) {


        if (keyaccountRes) {
            sales_number = keyaccountRes.sales_number += order_quantity;
        }
        let keyStatus = 0;
        if (!keyaccountRes) {
            sales_number = partnerRes.sales_volume += order_quantity
            keyStatus = 1
        }
        //向商品表添加审核通过数据
        for (let i = 1; i <= order_quantity; i++) {
            let card_header = ""
            let good_price = 0
            product_name == "年卡" ? card_header = "K" : card_header = "V"
            product_name == "年卡" ? good_price = 100 : good_price = 60
            let res = randow.getCardNumber(card_header)
            let activation_code = randow.getActication(8)
            let activation_date = Date.now() + 10000000;
            cardArr.push({ goodname: product_name, good_price: good_price, card_number: res, activation_code: activation_code, activation_date: activation_date, order_number: order_number })

        }
        if (keyword == 1) {
            let partnerChange
            //修改该订单的订单状态为通过
            let checkOrder = await orderModel.updateOne({ order_number: order_number }, { order_status: 1 })
            if (keyStatus == 1) {
                partnerChange = await partnerModel.updateOne({ partner_name: Sales_name }, { sales_volume: sales_number })
            } else {
                partnerChange = await keyaccountModel.updateOne({ Sales_name }, { sales_number: sales_number })
            }
            ctx.body = {
                code: 200,
                msg: "审核订单成功",
                partnerChange
            }
            //通过订单，并往商品表添加审核成功的数据
            let result = await goodsModel.create(cardArr)
        } else if (keyword == 0) {
            //修改该订单的状态为不通过
            let checkOrder = await orderModel.updateOne({ "order_number": order_number }, { "order_status": 0 })
            ctx.body = {
                code: 200,
                msg: "审核订单成功",
            }
        }
        else {
            ctx.body = {
                orderRes,
                msg: "修改订单状态失败,可能是由于订单还未支付"
            }
        }
    } else {
        ctx.body = {
            code: 400,
            msg: "修改订单状态失败,可能是提交了重复的操作",
        }
    }
})

//根据状态筛选订单
//传回数据：订单编号，订单数量，姓名，单位名称，创建时间，单价，支付金额，审核状态
//不传入参数则返回所有订单

router.post("/getOrderStatus", async (ctx) => {
    ctx.status = 200
    let data = ctx.request.body
    let { status } = data
    let res = await orderModel.find({})
    let tarArr = []
    res.forEach((item) => {
        item.hasPay = 0
        if (item.order_status == status) {
            tarArr.push(item)
        }
    })
    if (!status) {
        tarArr = res
    }
    let newData = []
    tarArr.forEach((item) => {
        //已支付计算支付金额
        if (item.pay_status == 1) {
            let tempPrice = 0;
            if (item.product_name == "年卡") {
                tempPrice = 100
            } else {
                tempPrice = 60
            }
            item.hasPay = item.order_quantity * tempPrice
        }
    })
    ctx.body = {
        code: 200,
        res: tarArr
    }
})
//根据传入数据筛选信息
router.post("/getOrders", async (ctx) => {
    ctx.status = 200
    let data = ctx.request.body
    let { name, company, orderType, cardType, startTime, endTime } = data

    let res = JSON.stringify(await orderModel.find({}))


    let ds = JSON.parse(res)
    if (name) {
        for (let i in ds) {
            if (ds[i].name != name) {
                ds.splice(i, 1, 1)
            }
        }
    }
    if (company) {
        for (let i in ds) {
            if (ds[i].company != company) {
                ds.splice(i, 1, 1)
            }
        }
    }
    if (orderType) {
        for (let i in ds) {
            if (ds[i].type != orderType) {
                ds.splice(i, 1, 1)
            }
        }
    }
    if (cardType) {
        for (let i in ds) {
            if (ds[i].card_type != cardType) {
                ds.splice(i, 1, 1)
            }
        }
    }
    if (endTime) {
        let timeds = screenArray(ds, "inOrOut", { startTime, endTime })
        ds = timeds
    }
    let dds = []
    ds.forEach((item) => {
        if (item != 1) {
            dds.push(item)
        }
    })
    ctx.body = {
        code: 200,
        res: dds
    }
})


//添加订单信息
router.post('/Orderform',async(ctx)=>{
    ctx.status=200
    console.log(ctx.request.body);
    data=ctx.request.body
    if(data.type=="合伙人"){
        let keycount=await partner.find({},function(err,docs){
            console.log(111,docs);         
            docs.forEach(item=>{
                if(item.partner_name==data.name&&data.order_status==1){
                    item.sales_volume+=data.order_quantity
                    console.log(333,"修改成功");
                    item.save()//调用save即可
                }
            })
        })
        data.order_number= randow.getOrderNumber(18)
        let res= await orderModel.create(data)
        ctx.body={
            code:200,
            msg:'添加成功',
            data:res
        }
    }else if(data.type=="大客户"){
        let dakehu= await AccountMOdel.find({},function(err,res){         
            res.forEach(item=>{
                if(item.Sales_name==data.name&&data.order_status==1){
                    item.sales_number+=data.order_quantity
                    console.log(222,"修改成功");
                    item.save()//调用save即可
                }
            })
        })
        data.order_number= randow.getOrderNumber(18)
        let res= await orderModel.create(data)
        ctx.body={
            code:200,
            msg:'添加成功',
            data:res
        }
    }
   

   
})

//根据选择日期查询该大客户详情里的订单
router.post('/getOrderFromDate',async (ctx)=>{
    ctx.status = 200

    let {name,dateParams} = ctx.request.body

    let orderList = await orderModel.find({name})

    console.log(orderList)

    let newArr = screenArray(orderList,"create_time",dateParams)

    console.log(newArr)

    ctx.body = {
        code:200,
        data:newArr
    }
})

//查询大客户详情里的订单详情
router.post('/getOrderInfo',async (ctx)=>{
    ctx.status = 200

    let {_id} = ctx.request.body

    let res = await OrderModel.findOne({_id})

    ctx.body = {
        code:200,
        data:res
    }
})

//获取大客户菜单的订单列表
router.get('/getAllOrder',async (ctx)=>{
    ctx.status = 200

    let res = await orderModel.find({})

    ctx.body = {
        code:200,
        data:res
    }
})

//查询大客户菜单的订单列表
router.post('/queryOrder', async (ctx) => {
    ctx.status = 200

    let {queryParams, dateParams} = ctx.request.body

    let res1 = await OrderModel.find(queryParams)

    if (dateParams != undefined) {
        res1 = screenArray(res1, "create_time", dateParams)
    }

    ctx.body = {
        code: 200,
        data: res1
    }
})

//根据订单编号获取订单详细信息
router.post('/getOdermsg',async (ctx) => {
    ctx.status = 200

    let {order_number} = ctx.request.body

    let res = await orderModel.findOne({order_number})

    ctx.body = {
        code:200,
        data:res
    }
})

module.exports = router















